#include "ListView.h"
#include "ui_ListView.h"

ListView::ListView(QWidget *parent) :
	INoteView(parent),
	ui(new Ui::ListView)
{
	ui->setupUi(this);
	connect(ui->listWidget,SIGNAL(itemSelectionChanged()),SLOT(onItemSelected()));
	connect(ui->btnAddNote,SIGNAL(clicked()),SIGNAL(onBtnAddNote()));
	connect(ui->btnRemoveNote,SIGNAL(clicked()),SLOT(onBtnRemoveItem()));

	connect(ui->btnEdit,SIGNAL(clicked()),SLOT(onBtnEdit()));

	ui->btnAddNote->setStyleSheet(getButtonStyle("add"));
	ui->btnRemoveNote->setStyleSheet(getButtonStyle("delete"));
	ui->btnEdit->setStyleSheet(getButtonStyle("edit"));
}

ListView::~ListView()
{
	delete ui;
}

void ListView::onNoteAdded(Note* note)
{
	QListWidgetItem* item = new QListWidgetItem(note->getUrl());
	item->setData(Qt::UserRole, qVariantFromValue((void *) note));
	ui->listWidget->insertItem(0, item);
	ui->listWidget->sortItems();
}

void ListView::onNoteRemoved(Note* note)
{
	for(int i=0; i<ui->listWidget->count(); i++){
		if( ui->listWidget->item(i)->data(Qt::UserRole) == qVariantFromValue((void *) note) ){
			ui->listWidget->takeItem(i);
			if(ui->listWidget->count() == 0){
				clearFields();
			}
			return;
		}
	}
}

void ListView::onNoteUpdated(Note* note)
{
	for(int i=0; i<ui->listWidget->count(); i++){
		if( ui->listWidget->item(i)->data(Qt::UserRole) == qVariantFromValue((void *) note) ){
			ui->listWidget->item(i)->setText(note->getUrl());
			QListWidgetItem* item = ui->listWidget->currentItem();
			if(item == NULL) return;
			Note* currNote = (Note*) item->data(Qt::UserRole).value<void*>();
			if(currNote == note){
				ui->editUrl->setText(note->getUrl());
				ui->editLogin->setText(note->getLogin());
				ui->editPass->setText(note->getPass());
				ui->editComment->setText(note->getComment());
			}
			ui->listWidget->sortItems();
			return;
		}
	}
}

void ListView::onItemSelected()
{
	QListWidgetItem* item = ui->listWidget->currentItem();
	if(item == NULL) return;

	Note* note = (Note*) item->data(Qt::UserRole).value<void*>();
	if(note == NULL) return;

	ui->editUrl->setText(note->getUrl());
	ui->editLogin->setText(note->getLogin());
	ui->editPass->setText(note->getPass());
	ui->editComment->setText(note->getComment());
}

void ListView::onBtnRemoveItem()
{
	QListWidgetItem* item = ui->listWidget->currentItem();
	if(item == NULL) return;
	Note* note = (Note*) item->data(Qt::UserRole).value<void*>();
	if(note == NULL) return;
	if(_provider){
		_provider->removeNote(note);
	}
}

void ListView::onBtnEdit()
{
	QListWidgetItem* item = ui->listWidget->currentItem();
	if(item == NULL) return;
	Note* note = (Note*) item->data(Qt::UserRole).value<void*>();
	if(note == NULL) return;
	emit onBtnEditNote(note);
}

void ListView::clearFields()
{
	if(ui->listWidget->count() == 1) return;
	ui->editComment->setText("");
	ui->editLogin->setText("");
	ui->editPass->setText("");
	ui->editUrl->setText("");
}
